<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="add">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="warning" @click="edit">编辑</el-button>
        <el-select v-model="selectedFilter" placeholder="请选择状态" style="width: 200px;">
          <el-option label="启用" value="enabled"></el-option>
          <el-option label="禁用" value="disabled"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" style="width: 200px;" />
        <el-button type="info" @click="query">查询</el-button>
        <el-button type="info" @click="query">重置</el-button>
      </div>
      <el-table :data="tableData" border class="eltable">
        <el-table-column prop="llck_zt" label="状态" width="80">
          <template #default="{ row }">
            <span v-if="row.llck_zt === 1">未出库</span>
            <span v-else-if="row.llck_zt === 2">已出库</span>
          </template>
        </el-table-column>
        <el-table-column prop="llck_code" label="领料出库单号"></el-table-column>
        <el-table-column prop="llck_lx" label="出库类型"></el-table-column>
        <el-table-column prop="llck_gdh" label="生产工单号"></el-table-column>
        <el-table-column prop="llck_jhllsj" label="计划领料时间">
          <template #default="{ row }">
            {{ formatDate(row.llck_jhllsj) }}
          </template>
        </el-table-column>
        <el-table-column prop="llck_bz" label="备注"></el-table-column>
        <el-table-column prop="user1_name" label="创建人"></el-table-column>
        <el-table-column prop="create_time" label="创建时间">
          <template #default="{ row }">
            {{ formatDate(row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button type="text" @click="xxtRow(row)">详细</el-button>
            <el-button type="text" @click="ckRow(row)" :disabled="row.llck_zt === 2">出库作业</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="增加" height="800">
    <el-form :model="form" :inline="true" class="demo-form-inline">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="领料出库单号">
            <el-input v-model="form.llck_code" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出库类型">
            <el-input v-model="form.llck_lx" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划领料时间">
            <el-date-picker v-model="form.llck_jhllsj" type="date" placeholder="选择日期" style="width: 100%" />
          </el-form-item>
          <!-- <el-date-picker v-model="form.yclcg_time" type="date" placeholder="请选择日期" /> -->
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="生产工单号">
            <el-select v-model="form.llck_gdh" placeholder="请选择工单号" clearable style="width: 200px;">
              <el-option v-for="item in workOrderOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注">
            <el-input v-model="form.llck_bz"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button type="primary" @click="addwl" style="float: right;">+添加物料</el-button>
    <el-table :data="xxtableData" border style="font-size: 80%;">
      <el-table-column type="index" label="序号" width="100" />
      <el-table-column prop="wl_code" label="物料编码"></el-table-column>
      <el-table-column prop="llckxx_wlmc" label="物料名称"></el-table-column>
      <el-table-column prop="llckxx_wlfl" label="物料分类"></el-table-column>
      <el-table-column prop="llckxx_ggxh" label="规格型号"></el-table-column>

      <el-table-column prop="llckxx_ckck" label="出库仓库">
        <template #default="{ row }">
          <el-select v-model="row.llckxx_ckck" placeholder="请选择">
            <el-option v-for="item in row.cktabe" :key="item.ck_code" :label="item.ck_name" :value="item.ck_code" />
          </el-select>
        </template>
      </el-table-column>

      <!-- 出库数量（输入框） -->
      <el-table-column prop="llckxx_cksl" label="出库数量">
        <template #default="{ row }">
          <el-input v-model="row.llckxx_cksl" placeholder="请输入" type="number" min="0"
            @input="handleInput(row)"></el-input>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addqr">确 定</el-button>
    </span>
  </el-dialog>
  <el-dialog v-model="materialDialogVisible" title="选择物料" width="80%">
    <el-table ref="materialTable" :data="materialList" @selection-change="handleMaterialSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="物料编码" prop="wl_code" />
      <el-table-column label="物料名称" prop="wl_name" />
      <el-table-column label="物料分类" prop="wl_fl_name" />
      <el-table-column label="物料规格" prop="wl_size" />
      <el-table-column label="物料单位" prop="wl_dw_name" />
    </el-table>

    <!-- 模态框底部按钮 -->
    <template #footer>
      <el-button @click="materialDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmMaterialSelection">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    const userId = localStorage.getItem('userId');
    const router = useRouter();
    const searchKey = ref('');
    const materialTable = ref(null);
    const treeData = ref([]);
    const defaultProps = {
      children: 'children',
      label: 'label',
    };
    // 格式化日期函数
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    };
    const tableData = ref([]);

    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(3);
    const dialogVisible = ref(false);
    const materialDialogVisible = ref(false);
    const materialList = ref([]);
    const selectedMaterials = ref([]); // 选中的物料
    const form = ref({
      llck_lx: '',
      llck_jhllsj: '',
      llck_code: '',
      llck_gdh: '',   // 添加缺失的字段
      llck_bz: ''     // 添加缺失的字段
    });
    let xxtableData = ref([

    ]);
    const workOrderOptions = ref([
    ]);
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
    const day = String(now.getDate()).padStart(2, '0'); // 补零

    // 生成四位随机数
    const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

    // 拼接时间字符串和随机数
    const formattedTime = `${year}${month}${day}`;
    let id = `llck${formattedTime}${randomNumber}`
    const setDefaultValue = () => {
      form.value.llck_code = id; // 随机单号示例
      form.value.llck_lx = '领料出库'; // 固定类型示例
    }
    function sx() {
      axios.get('/api/WMS_LLCK/Getllck?PageNumber=' + currentPage.value + '&pageSize=' + pageSize.value).then((response) => {
        console.log(response.data);
        tableData.value = response.data.wMS_LLCKs;
        totalItems.value = response.data.zon;
      }).catch((error) => {
        console.error('错误:', error);
      });
    }
    sx();
    const add = () => {
      form.value = {
        llck_code: '', // 领料出库单号
        llck_lx: '', // 出库类型
        llck_jhllsj: null, // 计划领料时间
        llck_gdh: '', // 生产工单号
        llck_bz: '' // 备注
      };
      // 重置表格数据
      xxtableData.value = [];
      dialogVisible.value = true;
      setDefaultValue();
      // 添加逻辑  
    };
    const openMaterialDialog = async () => {
      const response = await axios.get('/api/Mes_gdrw/GetMes_gdrw');
      console.log(response.data);
      workOrderOptions.value = response.data.map(item => ({
        label: item.gdrw_code, // 假设返回的数据中仓库名称字段为 name
        value: item.gdrw_code    // 假设返回的数据中仓库 ID 字段为 id
      }));
    };
    const addwl = () => {
      axios.get('/api/WL/CGWL').then((response) => {
        console.log(response.data);
        materialList.value = response.data;
      });
      materialDialogVisible.value = true;
    }
    const handleMaterialSelectionChange = (selection) => {
      console.log('Selected materials:', selection);
      selectedMaterials.value = selection;
    };
    const confirmMaterialSelection = async () => {
      if (selectedMaterials.value.length > 0) {
        selectedMaterials.value.forEach((material) => {
          // 检查物料是否已经存在
          const isMaterialExist = xxtableData.value.some(
            (item) => item.wl_code === material.wl_code
          );
          console.log(isMaterialExist);
          console.log('material', material);
          // 如果物料不存在，则添加到表格顶部
          if (!isMaterialExist) {
            axios.get('/api/WMS_KC/GetLLCKWMS_KC?code=' + material.wl_code).then((response) => {
              console.log("1111", response.data);
              xxtableData.value.unshift({
                wl_code: material.wl_code,
                llckxx_wlmc: material.wl_name,
                llckxx_wlfl: material.wl_fl_name,
                llckxx_ggxh: material.wl_size,
                llckxx_ckck: '',  // 初始化仓库选择
                llckxx_cksl: 0,  // 初始化数量
                cktabe: response.data,
                wl_dw: material.wl_dw,
                wl_fl: material.wl_fl
              });
            });

          }
        });
      }
      materialDialogVisible.value = false;
    };
    const addqr = async () => {
      try {
        console.log('Adding new row:', form.value);
        console.log('Adding new row:', xxtableData.value);
        // 第一个请求：添加主表数据
        const response = await axios.post('/api/WMS_LLCK/Addllck', {
          llck_code: form.value.llck_code,
          llck_lx: form.value.llck_lx,
          llck_jhllsj: form.value.llck_jhllsj,
          llck_gdh: form.value.llck_gdh,
          llck_bz: form.value.llck_bz,
          create_by: userId,
        });
        console.log(response.data);

        // 第二个请求：批量添加明细表数据
        const detailRequests = xxtableData.value.map(async (item) => {
          console.log(' row:', item);
          const response1 = await axios.post('/api/WMS_LLCKXX/Addllckxx', {
            wl_code: item.wl_code,
            llckxx_wlmc: item.llckxx_wlmc,
            llckxx_wlfl: item.wl_fl,
            llckxx_ggxh: item.llckxx_ggxh,
            llckxx_ckck: item.llckxx_ckck,
            llckxx_wldw: item.wl_dw,
            llckxx_cksl: item.llckxx_cksl,
            llck_code: form.value.llck_code,
          });
          console.log(response1.data);
          const cx = await axios.get('api/WMS_KC/GetWMS_KCCKDL?ck_code=' + item.llckxx_ckck + '&wl_code=' + item.wl_code);
          console.log('cx', cx.data.kc_id);


          const response2 = await axios.put('/api/WMS_KC/UpdateWMS_KC?id=' + cx.data.kc_id + '&sl=' + item.llckxx_cksl);
          console.log('response1', response2.data);
          return response1; // 返回每个请求的结果

        });

        // 使用 Promise.all 等待所有明细请求完成
        await Promise.all(detailRequests);

        // 所有请求成功后的处理
        ElMessage.success('添加成功');
      } catch (error) {

        // 任何一个请求失败时的处理
        console.error('错误:', error);
        ElMessage.error('添加失败，请检查数据后重试');
      }
      dialogVisible.value = false;
      sx();
    }
    const edit = () => {
      // 编辑逻辑  
    };


    const query = async () => {
      // 查询逻辑  
      console.log('Querying with:', searchTable.value);

    };

    const xxtRow = (row) => {
      console.log('Editing row:', row);
      // router.push({
      //   path: '/PickingWarehouseXX',
      //   query: { row: JSON.stringify(row) } // 将 row 序列化为 JSON 字符串
      // });
      router.push({
        name: 'PickingWarehouseXX',
        query: {
          llck_code: row.llck_code
        }
      });
    };

    const ckRow = (row) => {
      console.log('Deleting row:', row);
      router.push({
        path: '/CKPickingWarehouse',
        query: { row: JSON.stringify(row) } // 将 row 序列化为 JSON 字符串
      });
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      // 分页逻辑  
      console.log('Current page:', page);
      sx();
    };
    onMounted(() => {
      openMaterialDialog();
    });

    // 确保所有函数都被返回  
    return {
      searchKey,
      treeData,
      defaultProps,
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      add,
      edit,
      query,
      xxtRow,
      ckRow,
      handleCurrentChange,
      dialogVisible,
      form,
      xxtableData,
      setDefaultValue,
      workOrderOptions,
      addqr,
      materialDialogVisible,
      materialTable,
      addwl,
      materialList,
      selectedMaterials,
      handleMaterialSelectionChange,
      confirmMaterialSelection,
      formatDate
    };
  },
  methods: {
    handleInput(row) {
      console.log('Input:', row.cktabe);
      console.log('Input:', row.llckxx_cksl);
      const it = row.cktabe.find(item => item.ck_code == row.llckxx_ckck);
      console.log('Inputit:', it);
      const zd = it.kc_sl - it.kc_jhsl;
      console.log('zd', zd);
      if (row.llckxx_cksl > zd) {
        row.llckxx_cksl = zd;
      } else if (row.llckxx_rksl < 0) {
        row.llckxx_cksl = 0;
      }
      this.$forceUpdate();
    }
  }
};
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.sidebar {
  height: 100%;

}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 95%;
  font-size: 100%;
}

.letree {
  height: 100%;
}
</style>
